package com.example.demo.realm;

import com.example.demo.config.UserResourceProperties;
import com.example.demo.dao.CustomMapper;
import com.example.demo.dao.UserMapper;
import com.example.demo.entity.Privilege;
import com.example.demo.entity.Role;
import com.example.demo.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import tk.mybatis.mapper.entity.Example;

import java.util.List;

public class MyRealm extends AuthorizingRealm {


@Autowired
    private UserMapper userMapper;


@Autowired
private CustomMapper customMapper;


@Autowired
private UserResourceProperties resourceProperties;

//shouquan
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        User loginUser=(User)principalCollection.getPrimaryPrincipal();

       // Subject subject= SecurityUtils.getSubject();
        //subject.getSession().setAttribute("loginUser",loginUser);


        SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
        List<Role> roleList=customMapper.findRoleByUserId(loginUser.getUserId());
        for(Role role:roleList){

            authorizationInfo.addRole(role.getCode());
            List<Privilege>  privilegeList=customMapper.findPrivilegeByRoleId(role.getRole_id());
            for(Privilege privilege:privilegeList){
                authorizationInfo.addStringPermission(privilege.getCode());
            }
        }

        return authorizationInfo;
    }


    //yanzheng
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken token=(UsernamePasswordToken)authenticationToken;
      String username=(String) token.getPrincipal();
      String password=new String((char[])token.getCredentials());

        Example example=new Example(User.class);

        Example.Criteria criteria=example.createCriteria();

        criteria.andEqualTo("username",username);




        List<User> userList=userMapper.selectByExample(example);

        if(userList.size()==0)
            return null;
        else{

            User user=userList.get(0);

            AuthenticationInfo authenticationInfo=
                    new SimpleAuthenticationInfo(user,user.getPassword(),this.getName());

            return authenticationInfo;


        }







    }
}
